package com.leyou.sms.listener;

import com.aliyuncs.exceptions.ClientException;
import com.leyou.sms.config.SMSProperties;
import com.leyou.sms.utils.SMSUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import java.util.Map;

@Component
@EnableConfigurationProperties(SMSProperties.class)
public class SMSListener {
    @Autowired
    private SMSProperties prop;
    @Autowired
    private SMSUtils smsUtils;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "leyou.sms.queue",durable = "true"),
            exchange = @Exchange(value = "leyou.sms.exchange",ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC),
            key = {"sms.verify.code"}
    ))
    public void listenSMS(Map<String,String> msg) throws ClientException {
        if (CollectionUtils.isEmpty(msg)){
            return;//空消息
        }
        String phone = msg.get("phone");
        String code = msg.get("code");

        //StringUtils是Lang3的
        if (StringUtils.isNoneBlank(phone) && StringUtils.isNoneBlank(code)){
            this.smsUtils.sendSms(phone,code,prop.getSignName(),prop.getVerifyCodeTemplate());//返回的手机号和验证码为之一为空则取消发送
        }



    }




}
